/**
 * Created by yihua on 2017/2/16.
 */

/**
 * Created by yihua on 2017/2/7.
 */
$(document).ready(function () {
    init();
    var options = {
        url: '/home/shop/addad',
        beforeSubmit: validate,  // pre-submit callback
        success: showResponse,  // post-submit callback
        dataType: 'json',
        type: 'post',
    };
    var btn = $("#confirm");
    btn.unbind('click').click(function () {
        options.data = {
            'ad_code': $('#ad_code_img').data('url')
        }
        $("#addbannerimg").ajaxSubmit(options)
    });

    function validate(formData, jqForm, options) {
        console.log(options.data)
        for (var i = 0; i < formData.length; i++) {
            console.log(formData[i].name, formData[i].value);
            if ('file' == formData[i].type) {
                break;
            }
            if (!formData[i].value) {
                toastr.error('请输入所有选项', '', {positionClass: 'toast-bottom-center'});
                return false;
            }
        }

        console.log($('#ad_code_img').data('url'))
    }

    function showResponse(responseText) {
        if (0 !== responseText.errno) {
            toastr.error(responseText.errmsg, '', {positionClass: 'toast-bottom-center'});
        } else {
            toastr.success('成功', '', {positionClass: 'toast-bottom-center'});
            $('#myModal').modal("hide");
            window.location.reload();
        }
    }

    function init() {
        $("#ad_code_img").fileinput({
            uploadUrl: "/common/uploadimage", // server upload action
            uploadAsync: true,
            showPreview: false,
            showUpload: false,
            allowedFileExtensions: ['jpg', 'png', 'gif'],
            maxFileCount: 5,
        }).on('fileuploaded', function (event, data, id, index) {
            var ret = data.response;
            if (0 != ret.errno) {
                toastr.error('上传失败', '', {positionClass: 'toast-bottom-center'});
            }
            //$("#ad_code").val(ret.data.url)
            $("#ad_code_img").data('url', ret.data.url);
        }).on("filebatchselected", function (event, files) {
            $("#ad_code_img").fileinput("upload");
        });
    }
});